package com.testing.sunnycommon.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.testing.sunnycommon.model.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Classname SunnyAuthenticationEntryPoint
 * @Description 没有携带token的情况下的回调函数实现
 * @Date 2023/6/30 22:34
 * @Created by 特斯汀Roy
 */
@Component
public class SunnyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws  IOException {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        Result result = Result.fail(403, "您还没有登录，请登录后再请求对应资源",null);
        out.print(new ObjectMapper().writeValueAsString(result));
        out.flush();
        out.close();
    }
}
